import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectTest {
    @Test
    public void test1() throws Exception {
        //情况1，public
        Class clazz = Person.class;
        Person p1 = (Person) clazz.newInstance();
        Field ageField = clazz.getField("age");
        ageField.set(p1, 20);
        System.out.println(ageField.get(p1));
    }

    @Test
    public void test2() throws Exception {
        //情况2,private
        Class clazz = Person.class;
        Person p1 = (Person) clazz.newInstance();
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(p1, "jack");
        System.out.println(nameField.get(p1));
    }

    @Test
    public void test3() throws Exception {
        Class clazz = Person.class;
        Person p1 = (Person) clazz.newInstance();
        Field nationField = clazz.getDeclaredField("nation");
        nationField.setAccessible(true);
        nationField.set(null, "china");
        System.out.println(nationField.get(null));
        //同下
//        nationField.set(p1, "china");
//        System.out.println(nationField.get(p1));
    }

    @Test
    public void test4() throws Exception {
        //私有和共有方法
        Class clazz = Person.class;
        Person p1 = (Person)clazz.newInstance();

        Method pMethod = clazz.getDeclaredMethod("showName", String.class, int.class);
        pMethod.setAccessible(true);
        Object result = pMethod.invoke(p1, "jack", 19);
        System.out.println(result);
    }

    @Test
    public void test5() throws Exception {
        //调用静态方法
        Class clazz = Person.class;
        Person p1 = (Person)clazz.newInstance();
        Method sMethod = clazz.getDeclaredMethod("showSome");
        sMethod.setAccessible(true);
        //两种方法
        Object invoke1 = sMethod.invoke(p1);
        Object invoke2 = sMethod.invoke(null);
        System.out.println(invoke1);
        System.out.println(invoke2);
    }

    @Test
    public void test6() throws Exception {
        //调用构造器
        Class clazz = Person.class;
        Constructor declaredConstructor = clazz.getDeclaredConstructor(String.class, int.class);
        declaredConstructor.setAccessible(true);
        Person p1 = (Person) declaredConstructor.newInstance("jack", 19);
        System.out.println(p1);
    }
}
